package test;

public class 打破死锁 {
    public static class Main {
        public static void main(String[] args) {
            // 创建两个对象作为共享资源
            Object resource1 = new Object();
            Object resource2 = new Object();

            // 创建线程 1，让它占用 resource1 然后请求 resource2
            Thread thread1 = new Thread(() -> {
                synchronized (resource1) {
                    try {
                        Thread.sleep(1000);
                    } catch (InterruptedException e) {
                        System.out.println("Thread 1 is interrupted.");
                        return;
                    }

                    synchronized (resource2) {
                        System.out.println("Thread 1 has acquired resource 2.");
                    }
                }
            });

            // 创建线程 2，让它占用 resource2 然后请求 resource1
            Thread thread2 = new Thread(() -> {
                synchronized (resource2) {
                    try {
                        Thread.sleep(1000);
                    } catch (InterruptedException e) {
                        System.out.println("Thread 2 is interrupted.");
                        return;
                    }

                    synchronized (resource1) {
                        System.out.println("Thread 2 has acquired resource 1.");
                    }
                }
            });

            // 创建线程 3，在 10 秒钟后中断线程 1 和线程 2 并打破死锁状态
            Thread thread3 = new Thread(() -> {
                try {
                    Thread.sleep(1000);
                    thread1.interrupt();
                    thread2.interrupt();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            });

            // 启动线程
            thread1.start();
            thread2.start();
            thread3.start();
        }
    }

}
